<template>
  <div class="fx-avatar" :class="[typeof size==='string'?size:null,shape,{background:isBackground}]"
       :style="avatarStyle">
    <slot v-if="$slots.default||failStatus"></slot>
    <img v-else-if="src&&src!==''&&!failStatus" :src="src"
         :alt="$attrs.alt" :style="{objectFit:fit}" @error="failStatus=true">
    <i v-else-if="icon&&icon!==''&&!failStatus" class="fs18 iconfont" :class="icon"/>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, PropType, ref } from 'vue'
import { ComponentSize, componentSizeArr } from '@/base/types'

interface AvatarProps {
  src: string;
  size: ComponentSize | number;
  shape: 'circle' | 'square';
  fit: 'fill' | 'contain' | 'cover' | 'none' | 'scale-down';
  icon: string;
  background: string;
  isBackground: boolean;
}

export default defineComponent({
  name: 'FxAvatar',
  props: {
    // 图片地址
    src: {
      type: String as PropType<string>,
      default: null
    },
    // 大小
    size: {
      type: [String, Number] as PropType<ComponentSize | number>,
      default: 'default',
      validator (val: ComponentSize | number): boolean {
        if (typeof val === 'string') return componentSizeArr.includes(val)
        return Number.isInteger(val)
      }
    },
    // 头像样式
    shape: {
      type: String as PropType<'circle' | 'square'>,
      default: 'circle',
      validator (val: string): boolean {
        return ['circle', 'square'].includes(val)
      }
    },
    // 头像样式
    fit: {
      type: String as PropType<'fill' | 'contain' | 'cover' | 'none' | 'scale-down'>,
      default: 'contain',
      validator (val: string): boolean {
        return ['fill', 'contain', 'cover', 'none', 'scale-down'].includes(val)
      }
    },
    // icon
    icon: {
      type: String as PropType<string>,
      default: null
    },
    // 是否背景色
    isBackground: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    // 背景色
    background: {
      type: String as PropType<string>,
      default: null
    }
  },
  setup (props: AvatarProps) {
    // 头像样式
    const avatarStyle = computed(() => {
      if (typeof props.size === 'string') return null
      return {
        width: `${props.size}px`,
        height: `${props.size}px`,
        lineHeight: `${props.size}px`,
        backgroundColor: props.isBackground && props.background ? props.background : null
      }
    })
    // 加载错误状态
    const failStatus = ref<boolean>(false)

    return {
      avatarStyle,
      failStatus
    }
  }
})
</script>
